package com.easyj.base.security.service;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import com.easyj.admin.db.model.User;
import com.easyj.admin.sys.service.UserService;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.security.OnlineUser;
import com.easyj.base.security.SimpleUser;
import com.easyj.base.util.RemoteAddressUtil;
import com.fasterxml.jackson.databind.ObjectMapper;



@Service
public class DefaultAuthenticationSuccessHandler  implements AuthenticationSuccessHandler{

	@Autowired
	private UserService userService;
	@Autowired
	private ObjectMapper objectMapper;
	
	 @Autowired 
	 private  JCacheSecurityService securityService;
	 
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		
		//save login info
		SimpleUser us = ((SimpleUser) authentication.getPrincipal());
		String ip=RemoteAddressUtil.getIp(request);
		Date now=new Date();
		try {
			User user=new User();
			user.setId(us.getId());
			user.setLoginSuccess(true);
			user.setLoginErrCount(0);//失败次数
			user.setLoginIp(ip);
			user.setLoginTime(now);
			userService.saveLoginInfo(user);
		}catch(Exception ex) {
			//ex.printStackTrace();
		}
		

		 // 生成令牌
        final String token = TokenUtil.generateToken(us);
        
        // 保存在线信息
        OnlineUser line=new OnlineUser();
        line.setId(us.getId());
        line.setIp(ip);
        line.setDepartmentId(us.getDepartmentId());
        line.setLoginName(us.getUsername());
        line.setName(us.getName());
        line.setLoginTime(now);
        securityService.setOnlineUser(token, line);

		//return token
        Result result=Result.Success(token);
		String json = objectMapper.writeValueAsString(result);
	    response.setContentType("application/json;charset=UTF-8");
	    response.getWriter().write(json);
	}
	
	

}
